package controller

import (
	"gitee.com/kordar/goadmin/admin/enums"
	admin "gitee.com/kordar/goadmin/admin/form"
	model "gitee.com/kordar/goadmin/admin/models"
	"gitee.com/kordar/goadmin/admin/service"
	"github.com/gin-gonic/gin"
	"github.com/kordar/ginsys/util"
	response "github.com/kordar/goframework_resp"
	"github.com/spf13/cast"
)

type AdminController struct {
	service service.AdminService
}

func NewAdminController(service service.AdminService) *AdminController {
	return &AdminController{service: service}
}

// Register 注册管理员账号
func (c AdminController) Register(ctx *gin.Context) {
	f := admin.RegisterForm{}
	if err := util.DefaultGetValidParams(ctx, &f); err != nil {
		response.Error(ctx, err, nil)
		return
	}

	flag := c.service.Register(f)
	response.SuccessOrError(ctx, flag, "register success", "register fail")
}

// ResetPassword 重置密码
func (c AdminController) ResetPassword(ctx *gin.Context) {
	f := admin.ResetPasswordForm{}
	if err := util.DefaultGetValidParams(ctx, &f); err != nil {
		response.Error(ctx, err, nil)
		return
	}

	sysAdmin := ctx.MustGet(enums.AdminKey).(model.SysAdmin)
	flag := c.service.ResetPassword(f, sysAdmin)
	response.SuccessOrError(ctx, flag, "reset password success", "reset password fail")
}

// UploadAvatar 上传头像
func (c AdminController) UploadAvatar(ctx *gin.Context) {
	id := ctx.PostForm("id")
	file, err := ctx.FormFile("file")
	if err != nil {
		response.Error(ctx, err, nil)
		return
	}

	sysAdmin := ctx.MustGet(enums.AdminKey).(model.SysAdmin)
	flag := c.service.Avatar(cast.ToInt64(id), file, sysAdmin)
	response.SuccessOrError(ctx, flag, "upload success", "upload fail")
}
